package scheduler

import (
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntityManager"
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/commMqtt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/TimeInterval"
	"go-fox-edge-iot-fastbee/remote"
	"go-fox-edge-iot-fastbee/service"
	"time"
)

type deviceValuePushScheduler struct {
	timeInterval TimeInterval.TimeInterval
}

func (e *deviceValuePushScheduler) scheduler() {
	for true {
		time.Sleep(1 * time.Second)
		if !commEntityManager.EntityManager.Initialized {
			continue
		}

		e.do()
	}
}
func (e *deviceValuePushScheduler) do() {
	defer func() {
		if r := recover(); r != nil {
			commLogger.Console.Error(fmt.Sprintf("config() 捕获到异常:%v", r))
		}
	}()

	entityList, err := commEntityManager.GetEntityMap(commEntity.Type.DeviceEntity.Type())
	if err != nil {
		return
	}

	for _, entity := range entityList {
		deviceEntity := entity.(*commEntity.DeviceEntity)

		// 取出注册参数
		productId := deviceEntity.ExtendParam[service.FastBeeService.ProductId]
		deviceNum := deviceEntity.ExtendParam[service.FastBeeService.DeviceNum]
		if productId == nil || productId == "" || deviceNum == nil || deviceNum == "" {
			continue
		}

		// 检查：是否已经连接上云端的MQTT服务器
		clientId := remote.RemoteCloud.BuildClientId(productId, deviceNum)
		client := commMqtt.GetClient(clientId)
		if client == nil {
			continue
		}
		if !client.IsConnected() {
			continue
		}

		// 检查：计算整点时间间隔，是否已经到达
		timestamp, err := e.timeInterval.GetFixTime(time.Now().UnixMilli(), service.FastBeeService.TimeInterval, service.FastBeeService.TimeUnit)
		if err != nil {
			continue
		}
		timeInterval, err := e.timeInterval.Calculate(service.FastBeeService.TimeInterval, service.FastBeeService.TimeUnit)
		if err != nil {
			continue
		}
		if !e.timeInterval.TestLastTime(clientId, timestamp, timeInterval) {
			continue
		}

		val, err := commEntityManager.GetEntityByServiceKey(commEntity.Type.DeviceValueEntity.Type(), deviceEntity.MakeServiceKey())
		if err != nil || val == nil {
			continue
		}
		deviceValueEntity := val.(*commEntity.DeviceValueEntity)

		// 推送数据到云端
		remote.RemoteCloud.PublishDeviceValue(productId, deviceNum, deviceValueEntity.Params, timestamp)
	}

}
